package com.hunttown.mes.manage.controller.files;

import com.hunttown.mes.common.utils.GeneralUtils;
import com.hunttown.mes.common.utils.StringUtils;
import com.hunttown.mes.manage.service.TransportUploadFilesManageService;
import com.hunttown.mes.manage.service.files.FileSystemStorageManageService;
import com.hunttown.mes.rpc.domain.TransportUploadFilesDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @title: 文件预览和下载，前台可用
 * @author: wangjunfu
 * @date: 2022年12月01日 21:05
 * @description:
 */
@Controller
@RequestMapping(value = "/files/cos")
public class FileShowController {

    private final FileSystemStorageManageService fileSystemStorageManageService;
    private final TransportUploadFilesManageService uploadFilesService;

    @Autowired
    public FileShowController(FileSystemStorageManageService fileSystemStorageManageService, TransportUploadFilesManageService uploadFilesService) {
        this.fileSystemStorageManageService = fileSystemStorageManageService;
        this.uploadFilesService = uploadFilesService;
    }

    //region 下载

    /**
     * 下载
     *
     * @param id   文件Id（二选一）
     * @param etag 唯一标识（二选一）
     * @return 下载
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public ResponseEntity<Resource> downloadFile(Integer id, String etag) {
        Resource file = null;

        //非空判断
        if (StringUtils.intIsBlank(id) && StringUtils.isBlank(etag)) {
            return null;
        }

        //获取文件信息
        TransportUploadFilesDTO uploadFile = null;
        if (StringUtils.intIsNotBlank(id)) {
            uploadFile = uploadFilesService.getById(id);
        }

        if (uploadFile == null) {
            uploadFile = uploadFilesService.getByEtagWithoutEntId(etag);
        }

        if (uploadFile == null) {
            return null;
        }

        try {
            file = fileSystemStorageManageService.loadAsResource(uploadFile.getOnlyKey(), uploadFile.getAbsolutePath());
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        if (file != null) {
            return ((ResponseEntity.BodyBuilder) ResponseEntity.ok().header("Content-Disposition", new String[]{"attachment; filename=\"" + uploadFile.getFileName() + "\""})).body(file);
        }

        return null;
    }
    //endregion

    //region 浏览器直接预览或img中显示

    /**
     * 浏览器直接预览或img中显示
     *
     * @param response res
     * @param id       文件Id（二选一）
     * @param etag     唯一标识（二选一）
     */
    @RequestMapping(value = "/img", method = RequestMethod.GET)
    public void showFile(HttpServletResponse response, Integer id, String etag) {

        response.setCharacterEncoding("UTF-8");

        try {
            //非空判断
            if (StringUtils.intIsBlank(id) && StringUtils.isBlank(etag)) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "找不到相关资源");
                return;
            }

            //获取文件信息
            TransportUploadFilesDTO uploadFile = null;
            if (StringUtils.intIsNotBlank(id)) {
                uploadFile = uploadFilesService.getById(id);
            }

            if (uploadFile == null) {
                uploadFile = uploadFilesService.getByEtagWithoutEntId(etag);
            }

            if (uploadFile == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "找不到相关资源");
                return;
            }

            Resource file = fileSystemStorageManageService.loadAsResource(uploadFile.getOnlyKey(), uploadFile.getAbsolutePath());

            if (file != null) {
                response.reset();
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());

                //文件类型
                response.setContentType(uploadFile.getContentType());

                //通过文件类型判断是否要下载：图片和PDF直接预览，其它的下载
                String type = GeneralUtils.getContentType(uploadFile.getContentType());
                if (!type.equals("img") && !type.equals("pdf")) {
                    response.setHeader("Content-Disposition", "attachment;filename=" + new String(uploadFile.getFileName().getBytes("gb2312"), "ISO8859-1"));
                }

                byte[] buf = new byte[1024];
                InputStream in = file.getInputStream();

                int L;
                while ((L = in.read(buf)) != -1) {
                    toClient.write(buf, 0, L);
                }

                in.close();
                toClient.flush();
                toClient.close();

            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "找不到相关资源");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //endregion
}
